use crate::configuration;
use minio::s3::Client;
use minio::s3::creds::StaticProvider;
use minio::s3::http::BaseUrl;
use std::str::FromStr;
use std::sync::LazyLock;

/// 创建minio客户端
fn get_client() -> Client {
    let minio = configuration::minio();
    let url = minio.url();
    let ssl = minio.ssl();
    let host = minio.host();
    let port = minio.port();
    let region = minio.region();
    let access_key = minio.access_key();
    let secret_key = minio.secret_key();
    let base_url: &str = if url.is_some() {
        url.unwrap()
    } else {
         if ssl {
            &format!("https://{}:{}", host, port)
        } else {
            &format!("http://{}:{}", host, port)
        }
    };
    let base_url = BaseUrl::from_str(base_url);
    let mut base_url = match base_url {
        Ok(base_url) => base_url,
        Err(e) => panic!("minio连接解析错误: {}", e),
    };
    base_url.region = String::from(region);
    let static_provider = StaticProvider::new(access_key, secret_key, None);
    let client = Client::new(base_url, Some(Box::new(static_provider)), None, None);
    match client {
        Ok(client) => {
            log::info!("minio连接成功");
            client
        },
        Err(e) => panic!("minio连接错误: {}", e),
    }
}

static CLIENT: LazyLock<Client> = LazyLock::new(|| get_client());

/// 获取minio客户端
pub fn get() -> &'static Client {
    &CLIENT
}
